package top.magicpotato.sample.component;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.util.Duration;
import org.pomo.toasterfx.model.ToastParameter;
import top.magicpotato.sample.pojo.record.ConnectionInfo;
import top.magicpotato.sample.service.MainService;
import top.magicpotato.sample.store.DbStore;

import java.util.Optional;
import java.util.concurrent.CompletableFuture;

/**
 * 数据库右键菜单
 */
public class DbOptMenu extends ContextMenu {

    private static DbOptMenu instance = null;

    private TreeView<String> dbTreeView;

    private DbOptMenu() {
        MenuItem openItem = new MenuItem("连接");
        openItem.setOnAction(event -> {
            TreeItem<String> selectedItem = dbTreeView.getSelectionModel().getSelectedItem();
            MainService.getInstance().initTableTree(selectedItem);
        });

        MenuItem cloneItem = new MenuItem("克隆");
        cloneItem.setOnAction(event -> {
            TreeItem<String> selectedItem = dbTreeView.getSelectionModel().getSelectedItem();
            ConnectionInfo connectionInfo = DbStore.get(selectedItem.getValue());
            ConnectionDbDialog connectionDbDialog = ConnectionDbDialog.getInstance(connectionInfo);
            connectionDbDialog.show();
            connectionDbDialog.resultProperty().addListener((observable, oldValue, newValue) -> {
                DbStore.add(newValue);
                dbTreeView.getRoot().getChildren().add(new TreeItem<>(newValue.nickName()));
                ToastBar.getInstant().success("提示", "添加数据库成功", ToastParameter.builder().timeout(Duration.seconds(2)).build());
            });
//            Optional<ConnectionInfo> connectionInfoNew = connectionDbDialog.showAndWait();
//            connectionInfoNew.ifPresent(info -> {
//                // 连接信息存储起来
//                DbStore.add(info);
//                dbTreeView.getRoot().getChildren().add(new TreeItem<>(info.nickName()));
//                ToastBar.getInstant().success("提示", "添加数据库成功", ToastParameter.builder().timeout(Duration.seconds(2)).build());
//            });
        });

        MenuItem delItem = new MenuItem("删除");
        delItem.setOnAction(event -> {
            TreeItem<String> selectedItem = dbTreeView.getSelectionModel().getSelectedItem();
            dbTreeView.getRoot().getChildren().remove(selectedItem);
            // 异步持久化
            DbStore.getStore().remove(selectedItem.getValue());
            CompletableFuture.runAsync(DbStore::store);
        });
        getItems().addAll(openItem, cloneItem, delItem);
    }

    public static DbOptMenu getInstance(TreeView<String> dbTreeView) {
        // 单利模式，不需要考虑并发问题
        if (instance == null) {
            instance = new DbOptMenu();
        }
        instance.dbTreeView = dbTreeView;
        return instance;
    }
}
